package movie.alipay;

import java.io.UnsupportedEncodingException;

import org.springframework.stereotype.Component;

//import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;

import movie.entity.AlipayBean;

/**
 * 支付宝支付接口
 * @author CQUDJ
 *
 */
@Component
public class Alipay {
	public String pay(AlipayBean alipayBean) throws AlipayApiException, UnsupportedEncodingException {
		// 1、获得初始化的AlipayClient
		String serverUrl =AlipayConfig.getGatewayUrl();
		String appId =AlipayConfig.getApp_id();
		String privateKey =AlipayConfig.getMerchant_private_key();
		String format = "json";
		String charset =AlipayConfig.getCharset();
		String alipayPublicKey =AlipayConfig.getAlipay_public_key();
		String signType =AlipayConfig.getSign_type();
		String returnUrl =AlipayConfig.getReturn_url();
		String notifyUrl =AlipayConfig.getNotify_url();
		AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
		// 2、设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		
		// 页面跳转同步通知页面路径
		alipayRequest.setReturnUrl(returnUrl);
		// 服务器异步通知页面路径
		alipayRequest.setNotifyUrl(notifyUrl);
		
		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = new String(alipayBean.getOut_trade_no().getBytes("ISO-8859-1"),"UTF-8");
		//付款金额，必填
		String total_amount = new String(alipayBean.getTotal_amount().getBytes("ISO-8859-1"),"UTF-8");
		//订单名称，必填
		String subject = new String(alipayBean.getSubject().getBytes("ISO-8859-1"),"UTF-8");
		//商品描述，可空
		String body = new String(alipayBean.getBody().getBytes("ISO-8859-1"),"UTF-8");
		
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"body\":\""+ body +"\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
	
		// 3、请求支付宝进行付款，并获取支付结果
		String result = alipayClient.pageExecute(alipayRequest).getBody();		
		// 返回付款信息
		return result;
	}
}
